import jwt

SECRET_KEY = "rainbowInPaper"


def create_token(user_id, ip, permission):
    import datetime
    # 过期时间为7天
    datetime_int = datetime.datetime.utcnow() + datetime.timedelta(seconds=60 * 60 * 24 * 7)
    option = {
        "iss": "rainbowinpaper.com",  # token的签发者
        "exp": datetime_int,  # 过期时间
        "iat": datetime.datetime.utcnow(),
        "aud": "webkit",  # token的接收者，这里指定为浏览器
        "user_id": user_id,  # 放入用户信息，唯一标识，解析后可以使用该消息
        "permission": permission,  # 权限等级
        "ip": ip  # token与ip绑定
    }
    return jwt.encode(option, SECRET_KEY, "HS256")


def check_token(token):
    try:
        data = jwt.decode(token, SECRET_KEY, audience="webkit", algorithms=["HS256"])
        return data
    except jwt.ExpiredSignatureError:
        return None
    except jwt.DecodeError:
        return None
    except jwt.InvalidTokenError:
        return None
